<?php

declare(strict_types=1);

namespace app\customer\model;

use think\Model;

class CustomerContact extends Model
{
    // 定义数据表名
    // protected $name = 'customer_contact';

    // 定义主键
    protected $primaryKey = 'id';

    // 定义自动时间戳
    protected $autoIncrement = true;

    // 定义创建时间字段名
    protected $createTime = 'create_time';

    // 定义更新时间字段名
    protected $updateTime = 'update_time';

    // 定义数据类型
    protected $dataType = [
        'status' => 'int',
        'stage' => 'int',
        'tags' => 'string',
        'loss' => 'string',
        'curator' => 'string',
        'custype' => 'string',
        'cusnature' => 'string',
        'source' => 'string',
        'att_path' => 'string',
        'remark' => 'string',
        'is_del' => 'int',
    ];

    // 定义默认值
    protected $default = [
        'status' => 0,
        'stage' => 0,
        'tags' => '',
        'loss' => '',
        'curator' => '',
        'custype' => '',
        'cusnature' => '',
        'source' => '',
        'att_path' => '',
        'remark' => '',
        'is_del' => 0,
    ];

    // 定义关联方法
    public function creator()
    {
        // 假设'creator'是外键字段，'id'是Customer模型的主键
        return $this->belongsTo('Customer', 'creator', 'id');
    }

    public function updater()
    {
        // 假设'updater'是外键字段，'id'是Customer模型的主键
        return $this->belongsTo('Customer', 'updater', 'id');
    }

    // 定义获取器
    public function getCreatorValueAttr($value, $data)
    {
        return $this->getRelatedCustomerName('creator');
    }

    public function getUpdaterValueAttr($value, $data)
    {
        return $this->getRelatedCustomerName('updater');
    }

    // 私有辅助方法
    private function getRelatedCustomerName($relationName)
    {
        $relation = $this->getRelation($relationName);

        if (!$relation) {
            $relation = $this->$relationName()->find();
        }

        return $relation ? $relation->cusname : null;
    }


    public function getCusidValueAttr($value, $data)
    {

        if (is_null($data['cusid']) || '' == $data['cusid']) {
            return [];
        }
        $cus = Customer::where(['id' => $data['cusid']])->field('cusname')->select()->toArray();
        return implode(',', array_column($cus, 'cusname'));
    }
}
